package com.hubu.admin.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hubu.admin.entity.SecurityUser;
import com.hubu.admin.entity.User;
import com.hubu.admin.utils.JwtUtils;
import com.hubu.admin.utils.Result;
import com.hubu.admin.utils.ResultCode;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.rmi.server.ExportException;
import java.util.Objects;

//问题分析:Filter在Controller之前，Controller层的异常捕获，是无法捕获到还没有请求到Controller时发生的异常的。
//解决方案:如果要捕获Filter异常，只能通过控制器层定义的全局异常处理来捕获；那么也就只能想办法让Filter中的异常发送到Controller，再由Controller抛出异常，最后由全局异常捕获
//https://www.bilibili.com/video/BV1fN4y1u7ut/?p=11&spm_id_from=pageDriver
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {


        String requestURI = request.getRequestURI();
        /**
         * 登录接口直接放行
         */
        if ("/login".equals(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        //不是登录接口，需要获取token并对token进行验证
        //获取请求头中的token
        String token = request.getHeader("token");

        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }


        log.info("token:{}", token);
        String userId = null;
        Claims claims = null;
        try {
            claims = jwtUtils.parseJWT(token);
            userId = claims.getSubject();
        } catch (MalformedJwtException|ExpiredJwtException|SignatureException e) {
           response= Result.setReturnJson(response, e.getMessage());
           return ;
        }


        //根据userId从redis中获取用户信息，如果没有该用户就代表该用户没有登录过
        SecurityUser securityUser = (SecurityUser) redisTemplate.opsForValue().get("login" + userId);
        if (Objects.isNull(securityUser)) {
            logger.error("用户未登录");
            response=Result.setReturnJson(response, "用户未登录");
            return;
        }

        User user = securityUser.getUser();
        log.info("成功获取到用户信息:{}", user);

        //将用户信息存放在SecurityContextHolder.getContext()，后面的过滤器就可以获得用户信息了。
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, null, null);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(request, response);
    }

 }
